import store from '@/store'
// import Layout from '@/layout'
import { asyncRoutes } from '@/router'
import router from '@/router'
import { resetRouter } from '@/router'

export default async function refreshRoutes() {
  const routerType = store.getters.routerType
  const result = await store.dispatch('user/getUserInfo')
  const res = result.data;
  // 筛选出来可以访问的路由
  // const filterRoutes = asyncRoutes
  store.commit('user/setRoutes', [])
  // 动态路由添加规则
  resetRouter()
  const filterRoutes = []
  if(result.code === 200) {
    asyncRoutes.forEach(item => {
      if (res.menuList.some(it => {
        // return (it.url === item.name && item.meta.routerType === routerType)
        return it.url === item.name
      })) {
        filterRoutes.push({
          path: item.path,
          alwaysShow: true,
          component: item.component,
          redirect: item.redirect,
          hidden: !(item.meta.routerType === routerType),
          name: item.name,
          meta: item.meta,
          children: [...item.children]
        })
      }
    })
    // 筛选子路由不带排序
    filterRoutes.forEach(item => {
      item.children = item.children.filter(child => {
        // return res.menuList.some(it => {
        //   child.meta.sort = it.sort
        //   return it.url === child.name
        // }) || res.permissionList.some(ele => { // 筛选hidden-true的路由
        //   return ele === child.meta.anniu
        // })
        return res.permissionList.some(ele => { // 筛选hidden-true的路由
          child.meta.sort = ele.sort
          return ele === child.meta.anniu
        })
      })
    })
    // 调用修改用户可以访问路由规则的mutation
    filterRoutes.forEach(item => {
      item.children.sort((a, b) => {
        return a.meta.sort - b.meta.sort
      })
    })
  }
  // 调用修改用户可以访问路由规则的mutation
  store.commit('user/setRoutes', filterRoutes)
  router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
}
